<?php
/**
 * 商家管理店铺
 */
namespace app\ais\controller\api\v1;
use app\ais\controller\api\Base;
use app\ais\model\AisStore;
use app\ais\model\AisStoreBill;
use app\ais\model\AisStoreGroup;
use app\ais\model\AisStoreUnion;
use app\ais\model\AisCouponUser;
use app\ais\model\AisOrder;
use app\ais\model\AisCoupon;
use think\helper\Time;
use filter\Filter;

class Gmstore extends Base{

    protected $store;

    public function initialize() {
        parent::initialize();
        $this->isUserAuth();
        $this->store = AisStore::manageStore($this->user->id);
        if(empty($this->store)){
            exit(json_encode(['code' => 403,'msg'=>'无法找到该商家']));
        }
    }

    /**
     * 申请入驻商家/修改商家信息
     */
    public function edit(){
        if (request()->isPost()) {
            $param = [
                'name'      => $this->request->param('name/s'),
                'address'   => $this->request->param('address/s'),
                'telphone'  => $this->request->param('telphone/s'),
                'mch_id'    => $this->request->param('mch_id/d',''),
                'latitude'  => $this->request->param('latitude/s'),
                'longitude' => $this->request->param('longitude/s'),
                'imgs'      => $this->request->param('imgs/s','[]','htmlspecialchars_decode'),
            ];
            $this->apiSign($param);
            $validate = $this->validate($param,'Store.gmedit');
            if(true !== $validate){
                return enjson(403,$validate);
            }
            $imgs  = Filter::filter_escape(json_decode($param['imgs'],true));
            if(!empty($imgs)){
                $data['img']   = $imgs[0];
            }  
            $data['name']      = $param['name'];
            $data['telphone']  = $param['telphone'];
            $data['mch_id']    = $param['mch_id'];
            $data['address']   = $param['address'];
            $data['latitude']  = $param['latitude'];
            $data['longitude'] = $param['longitude'];
            $rel = AisStore::where(['id' => $this->store->id])->update($data);
            if($rel){
                return enjson(200,"成功");
            }
            return enjson(403,"失败");
        }
    }

    //读取商家信息
    public function read(){
        $this->apiSign();
        return enjson(200,$this->store);
    }

    //商家数据统计
    public function statis(){
        $this->apiSign();
        list($start, $end) = Time::yesterday();
        $amount     = AisOrder::where([['store_id','=', $this->store->id],['state', '=',1],['update_time', '>=',$start],['update_time', '<=',$end]])->sum('price');
        $coupon     = AisCoupon::where(['store_id' => $this->store->id])->count(); //已领取
        $couponuser = AisCouponUser::where(['store_id' => $this->store->id])->where('parent_store_id','>',0)->count(); //引流
        $from       = AisCouponUser::where([['store_id', '=', $this->store->id],['parent_store_id', '>',0],['money', '>',0],['is_end', '=',1]])->count(); //引流
        return enjson(200,['store'=>$this->store,'amount' => $amount,'coupon'=>$coupon,'couponuser' => $couponuser,'from'=> $from]);
    }

    //商家收入
    public function bill(){
        $param = [
            'page'           => $this->request->param('page/d',1),
            'store_id'       => $this->request->param('store_id'),
            'store_chain_id' => $this->request->param('store_chain_id'),
            'fixed_date'     => $this->request->param('fixed_date'),
            'times'          => $this->request->param('times','[]','htmlspecialchars_decode'),
        ];
        $this->apiSign($param);
        //判断是修改还是创建
        $store = AisStore::manageStore($this->user->id);
        if (!$store) {
            return enjson(404);
        }
        $condition[] = ['member_miniapp_id','=',$this->miniapp_id];
        $condition[] = ['store_id', '=',$this->store->id];
        if($param['store_chain_id']){
            $condition[] = ['store_chain_id', '=',$param['store_chain_id']];
        }
        if($param['fixed_date'] == 3){
            $times = Filter::filter_escape(json_decode($param['times'],true));
            if(!empty($times['startime']) || !empty($times['endtime'])){
                $start  = strtotime($times['startime'].'00:00:00');
                $end   = strtotime($times['endtime'].'23:59:59');
                if($start >= $end){
                    return enjson(403,'开启日期禁止大于结束日期');
                } 
                $condition[] = ['update_time', '>=', $start];
                $condition[] = ['update_time', '<=', $end];
            }
        }else{
            switch ($param['fixed_date']) {
                case 1:
                    list($start, $end) = Time::yesterday();
                    break;
                case 2:
                     list($start, $end) = Time::month();
                    break;
                default:
                    list($start, $end) = Time::today();
                    break;
            }
            $condition[] = ['update_time', '>=', $start];
            $condition[] = ['update_time', '<=', $end];
        }
        $rel = AisStoreBill::withAttr('update_time', function ($value, $data) {
            return date('Y-m-d H:i',$value);
        })->with(['user'=> function($query) {
            $query->field('id,face,nickname');
        }])->where($condition)->order('id desc')->page($param['page'],20)->select();
        if (empty($rel)) {
            return enjson(204);
        }
        $amount['inc']   = 0;
        $amount['dec']   = 0;
        $amount['order'] = 0;
        if($param['page'] == 1){
            $amount['inc']   = AisStoreBill::where($condition)->where('money','>',0)->sum('money');
            $amount['dec']   = AisStoreBill::where($condition)->where('money','<',0)->sum('money');
            $amount['order'] = AisOrder::where($condition)->where('state','=',1)->sum('price');
        }
        return enjson(200,['bill' => $rel,'amount' => $amount]);
    }
}